﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
//
using TagLib;
using TagLib.Id3v2;
using TagLib.Flac;
/*
Copyright 2010 Mirosław M. Mączka

This file is part of Flac2Wma.

    Flac2Wma is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Foobar is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Foobar; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/
namespace Flac2Wma
{
    public class Handler_Tag
    {
        /*
            Format:  FLAC
            Details: 44100 Hz Stereo, 657 kbps, playtime 01:43
            Tag:     FLAC
            Title:   The Village
            Artist:  Brian Tyler
            Album:   Rambo
            Year:    2008
            Track:   9
            Genre:   Soundtrack
            Comment:
            Description=TEAM T.L.R
            Source=CD (Lossless)
            Encoder=FLAC 1.2.1
            Encoder Settings=-compression-level-8 -verify
         */
        /*
TITLE Track/Work name
VERSION The version field may be used to differentiate multiple versions of the same track title in a single collection. (e.g. remix info)
ALBUM The collection name to which this track belongs
TRACKNUMBER The track number of this piece if part of a specific larger collection or album
ARTIST The artist generally considered responsible for the work. In popular music this is usually the performing band or singer. For classical music it would be the composer. For an audio book it would be the author of the original text.
PERFORMER The artist(s) who performed the work. In classical music this would be the conductor, orchestra, soloists. In an audio book it would be the actor who did the reading. In popular music this is typically the same as the ARTIST and is omitted.
COPYRIGHT Copyright attribution, e.g., '2001 Nobody's Band' or '1999 Jack Moffitt'
LICENSE License information, eg, 'All Rights Reserved', 'Any Use Permitted', a URL to a license such as a Creative Commons license ("www.creativecommons.org/blahblah/license.html") or the EFF Open Audio License ('distributed under the terms of the Open Audio License. see http://www.eff.org/IP/Open_licenses/eff_oal.html for details'), etc.
ORGANIZATION Name of the organization producing the track (i.e. the 'record label')
DESCRIPTION A short text description of the contents
GENRE A short text indication of music genre
DATE Date the track was recorded
LOCATION Location where track was recorded
CONTACT Contact information for the creators or distributors of the track. This could be a URL, an email address, the physical address of the producing label.
ISRC ISRC number for the track; see {the ISRC intro page} for more information on ISRC numbers.
         */
        //
        //
        public string Title { get; set; }
        public string Version { get; set; }
        public string Album { get; set; }
        public string TrackNumber { get; set; }
        public string Artist { get; set; }
        public string Performer { get; set; }
        public string Copyright { get; set; }
        public string License { get; set; }
        public string Organization { get; set; }
        public string Description { get; set; }
        public string Genre { get; set; }
        public string Date { get; set; }
        public string Location { get; set; }
        public string Contact { get; set; }
        public string Isrc { get; set; }
        //
        /// <summary>
        /// Error message from exception
        /// </summary>
        public string ErrorMessage { get; set; }
        /// <summary>
        /// true if file is without metadata
        /// </summary>
        public bool NoMetadata { get; set; }
        //
        private TagLib.File tagFile = null;
        //
        private void clearProps()
        {
            Title = string.Empty;
            Version = string.Empty;
            Album = string.Empty;
            TrackNumber = string.Empty;
            Artist = string.Empty;
            Performer = string.Empty;
            Copyright = string.Empty;
            License = string.Empty;
            Organization = string.Empty;
            Description = string.Empty;
            Genre = string.Empty;
            Date = string.Empty;
            Location = string.Empty;
            Contact = string.Empty;
            Isrc = string.Empty;
        }
        //
        public bool Do(string flacPathName)
        {
            //
            clearProps();
            //
            NoMetadata = true;
            ErrorMessage = "";
            //
            //
            string[] infoFromDir = flacPathName.Split(new char[] { '\\' });
            if (infoFromDir.Length >= 3)
            {
                Album = infoFromDir[infoFromDir.Length - 2].TrimEnd(new char[] { '~' });
                Artist = infoFromDir[infoFromDir.Length - 3].Trim();
            }
            //
            try
            {
                //
                if (System.IO.File.Exists(flacPathName))
                {
                    System.IO.FileAttributes fa = System.IO.File.GetAttributes(flacPathName);
                    fa = fa & ~System.IO.FileAttributes.ReadOnly;
                    System.IO.File.SetAttributes(flacPathName, fa);
                }
                //
                //
                tagFile = TagLib.File.Create(flacPathName);
                //
            }
            catch(Exception e)
            {
                ErrorMessage = "TagLib.File.Create(" + flacPathName + ")" + ": " + e.Message;
                return false;
            }
            //
            try{
                //TagLib.Tag tf = tagFile.GetTag(TagTypes.FlacMetadata, false);
                //
                if (null != tagFile.Tag.Title)
                {
                    Title = tagFile.Tag.Title;
                    NoMetadata = false;
                }
                //
                if (null != tagFile.Tag.Album)
                {
                    Album = tagFile.Tag.Album;
                    NoMetadata = false;
                }
                //
                TrackNumber = string.Format("{0:00}", tagFile.Tag.Track);
                //
                if (null != tagFile.Tag.AlbumArtists)
                {
                    if (tagFile.Tag.AlbumArtists.GetLength(0) > 0)
                    {
                        Artist = string.Join(", ", tagFile.Tag.AlbumArtists);
                        NoMetadata = false;
                    }
                    else
                    {
                        //
                        if (null != tagFile.Tag.Artists)
                        {
                            Artist = string.Join(", ", tagFile.Tag.Artists);
                            NoMetadata = false;
                        }
                        //
                    }
                }
                //
                if (0 != tagFile.Tag.Year) Date = tagFile.Tag.Year.ToString();
                //
                if (null != tagFile.Tag.Genres)
                {
                    Genre = string.Join(", ", tagFile.Tag.Genres);
                    NoMetadata = false;
                }
                //
                if (null != tagFile.Tag.Performers)
                {
                    Performer = string.Join(", ", tagFile.Tag.Performers);
                    NoMetadata = false;
                }
                //
                //
            }
            catch (Exception e)
            {
                ErrorMessage = e.Message;
                return false;
            }
            finally
            {
                tagFile = null;
            }
            //
            return true;
        }
        //
        //
    }//class
}//namespace
